<template>
  <div class="contract-review-page">
    <div class="page-header">
      <h2>合同审核</h2>
      <el-button type="primary" @click="handleRefresh">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>

    <!-- 搜索筛选 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" inline>
        <el-form-item label="合同编号">
          <el-input
            v-model="filterForm.contract_no"
            placeholder="请输入合同编号"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input
            v-model="filterForm.customer_name"
            placeholder="请输入客户名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="合同类型">
          <el-select
            v-model="filterForm.contract_type"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="销售合同" :value="1" />
            <el-option label="采购合同" :value="2" />
            <el-option label="服务合同" :value="3" />
            <el-option label="其他" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="审核状态">
          <el-select
            v-model="filterForm.status"
            placeholder="请选择"
            clearable
            style="width: 150px"
          >
            <el-option label="待审核" :value="1" />
            <el-option label="审核通过" :value="2" />
            <el-option label="审核驳回" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <el-row :gutter="16" class="stats-row">
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon" style="background: #409eff">
              <el-icon><Document /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">待审核</div>
              <div class="stat-value">{{ stats.pending }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon" style="background: #67c23a">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">已通过</div>
              <div class="stat-value">{{ stats.approved }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon" style="background: #f56c6c">
              <el-icon><Close /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">已驳回</div>
              <div class="stat-value">{{ stats.rejected }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <div class="stat-item">
            <div class="stat-icon" style="background: #e6a23c">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">总计</div>
              <div class="stat-value">{{ stats.total }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table :data="contractList" v-loading="loading" stripe style="width: 100%">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="contract_no" label="合同编号" width="180" />
        <el-table-column prop="customer_name" label="客户名称" min-width="150" />
        <el-table-column prop="contract_type" label="合同类型" width="120">
          <template #default="scope">
            <el-tag v-if="scope.row.contract_type === 1" type="primary">销售合同</el-tag>
            <el-tag v-else-if="scope.row.contract_type === 2" type="success">采购合同</el-tag>
            <el-tag v-else-if="scope.row.contract_type === 3" type="warning">服务合同</el-tag>
            <el-tag v-else type="info">其他</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="合同金额" width="120">
          <template #default="scope">¥{{ scope.row.amount?.toFixed(2) || '0.00' }}</template>
        </el-table-column>
        <el-table-column prop="status" label="审核状态" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="warning">待审核</el-tag>
            <el-tag v-else-if="scope.row.status === 2" type="success">审核通过</el-tag>
            <el-tag v-else-if="scope.row.status === 3" type="danger">审核驳回</el-tag>
            <el-tag v-else type="info">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="submit_time" label="提交时间" width="160">
          <template #default="scope">
            {{ formatDateTime(scope.row.submit_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="review_time" label="审核时间" width="160">
          <template #default="scope">
            {{ scope.row.review_time ? formatDateTime(scope.row.review_time) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              v-if="scope.row.status === 1"
              type="primary"
              size="small"
              @click="handleReview(scope.row)"
            >
              审核
            </el-button>
            <el-button type="info" size="small" @click="handleView(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="reviewDialogVisible"
      title="合同审核"
      width="600px"
      @close="resetReviewForm"
    >
      <el-form :model="reviewForm" :rules="reviewRules" ref="reviewFormRef" label-width="100px">
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="reviewForm.status">
            <el-radio :value="2">通过</el-radio>
            <el-radio :value="3">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="review_comment">
          <el-input
            v-model="reviewForm.review_comment"
            type="textarea"
            :rows="4"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="reviewDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmitReview" :loading="submitting">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage } from 'element-plus'
  import { Document, Check, Close, TrendCharts, Refresh } from '@element-plus/icons-vue'
  import type { FormInstance, FormRules } from 'element-plus'

  // 类型定义
  interface Contract {
    id: number
    contract_no: string
    customer_name: string
    contract_type: number
    amount: number
    status: number
    submit_time: number
    review_time?: number
  }

  // 统计数据
  const stats = reactive({
    pending: 0,
    approved: 0,
    rejected: 0,
    total: 0,
  })

  // 筛选表单
  const filterForm = reactive({
    contract_no: '',
    customer_name: '',
    contract_type: null as number | null,
    status: null as number | null,
  })

  // 审核表单
  const reviewForm = reactive({
    id: 0,
    status: 2,
    review_comment: '',
  })

  const reviewRules: FormRules = {
    status: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
    review_comment: [{ required: true, message: '请输入审核意见', trigger: 'blur' }],
  }

  // 引用
  const reviewFormRef = ref<FormInstance>()

  // 响应式数据
  const loading = ref(false)
  const submitting = ref(false)
  const reviewDialogVisible = ref(false)
  const contractList = ref<Contract[]>([])

  // 分页
  const pagination = reactive({
    page: 1,
    pageSize: 20,
    total: 0,
  })

  // 生命周期
  onMounted(() => {
    fetchContractList()
    fetchStats()
  })

  // 获取合同列表
  const fetchContractList = async () => {
    loading.value = true
    try {
      const params: any = {
        page: pagination.page,
        limit: pagination.pageSize,
      }

      if (filterForm.contract_no) params.contract_no = filterForm.contract_no
      if (filterForm.customer_name) params.customer_name = filterForm.customer_name
      if (filterForm.contract_type) params.contract_type = filterForm.contract_type
      if (filterForm.status) params.status = filterForm.status

      const request = (await import('@/utils/request')).default
      const res = await request({
        url: '/api/crm/contract/list',
        method: 'get',
        params,
      })

      if (res.data.code === 0) {
        contractList.value = res.data.data.list || []
        pagination.total = res.data.data.total || 0
      } else {
        ElMessage.error(res.data.msg || '获取合同列表失败')
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('获取合同列表失败')
    } finally {
      loading.value = false
    }
  }

  // 获取统计数据
  const fetchStats = async () => {
    try {
      const request = (await import('@/utils/request')).default
      const res = await request({
        url: '/api/crm/contract/stats',
        method: 'get',
      })

      if (res.data.code === 0) {
        const statsData = res.data.data || {}
        stats.pending = statsData.pending || 0
        stats.approved = statsData.approved || 0
        stats.rejected = statsData.rejected || 0
        stats.total = statsData.total || 0
      }
    } catch (error) {
      console.error(error)
    }
  }

  // 搜索
  const handleSearch = () => {
    pagination.page = 1
    fetchContractList()
    fetchStats()
  }

  // 重置
  const handleReset = () => {
    filterForm.contract_no = ''
    filterForm.customer_name = ''
    filterForm.contract_type = null
    filterForm.status = null
    handleSearch()
  }

  // 刷新
  const handleRefresh = () => {
    fetchContractList()
    fetchStats()
  }

  // 查看
  const handleView = (row: Contract) => {
    console.log('查看合同:', row)
    ElMessage.info('查看功能开发中')
  }

  // 审核
  const handleReview = (row: Contract) => {
    reviewForm.id = row.id
    reviewForm.status = 2
    reviewForm.review_comment = ''
    reviewDialogVisible.value = true
  }

  // 提交审核
  const handleSubmitReview = async () => {
    if (!reviewFormRef.value) return

    await reviewFormRef.value.validate(async valid => {
      if (valid) {
        submitting.value = true
        try {
          const request = (await import('@/utils/request')).default
          const res = await request({
            url: `/api/crm/contract/review/${reviewForm.id}`,
            method: 'post',
            data: {
              status: reviewForm.status,
              review_comment: reviewForm.review_comment,
            },
          })

          if (res.data.code === 0) {
            ElMessage.success('审核提交成功')
            reviewDialogVisible.value = false
            fetchContractList()
            fetchStats()
          } else {
            ElMessage.error(res.data.msg || '审核提交失败')
          }
        } catch (error) {
          console.error(error)
          ElMessage.error('审核提交失败')
        } finally {
          submitting.value = false
        }
      }
    })
  }

  // 重置审核表单
  const resetReviewForm = () => {
    reviewForm.id = 0
    reviewForm.status = 2
    reviewForm.review_comment = ''
    if (reviewFormRef.value) {
      reviewFormRef.value.resetFields()
    }
  }

  // 分页变化
  const handleSizeChange = (size: number) => {
    pagination.pageSize = size
    fetchContractList()
  }

  const handleCurrentChange = (page: number) => {
    pagination.page = page
    fetchContractList()
  }

  // 格式化日期
  const formatDateTime = (timestamp: number) => {
    if (!timestamp) return ''
    const date = new Date(timestamp * 1000)
    return date.toLocaleString()
  }
</script>

<style lang="scss" scoped>
  .contract-review-page {
    padding: 20px;

    .page-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      h2 {
        margin: 0;
        font-size: 20px;
        font-weight: 500;
      }
    }

    .filter-card {
      margin-bottom: 20px;
    }

    .stats-row {
      margin-bottom: 20px;

      .stat-item {
        display: flex;
        align-items: center;
        gap: 15px;

        .stat-icon {
          width: 50px;
          height: 50px;
          border-radius: 8px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: 24px;
        }

        .stat-content {
          .stat-label {
            font-size: 14px;
            color: #666;
            margin-bottom: 5px;
          }

          .stat-value {
            font-size: 24px;
            font-weight: bold;
            color: #333;
          }
        }
      }
    }

    .table-card {
      .pagination {
        margin-top: 20px;
        display: flex;
        justify-content: flex-end;
      }
    }
  }
</style>
